<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="圈子名称" prop="circleId">
        <el-select
          v-model="queryParams.circleId"
          placeholder="请选择圈子"
          filterable
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="circle in circleOptions"
            :key="circle.id"
            :label="circle.name"
            :value="circle.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="AI生成文章标题" prop="generatedTextId" class="generated_title">
        <el-select
          v-model="queryParams.generatedTextId"
          placeholder="请选择AI生成文章"
          filterable
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="digest in digestOptions"
            :key="digest.id"
            :label="digest.title"
            :value="digest.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="推送时间" prop="pushTime">
        <el-date-picker clearable
          v-model="queryParams.pushTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择推送时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="推送状态" prop="pushStatus" class="push-status">
        <el-select v-model="queryParams.pushStatus" placeholder="请选择推送状态" clearable>
          <el-option
            v-for="dict in pushStatusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pushRecord:pushRecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pushRecord:pushRecord:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pushRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="圈子名称" align="center" prop="circleId">
        <template #default="scope">
          {{ getCircleNameById(scope.row.circleId) }}
        </template>
      </el-table-column>
      <el-table-column label="AI生成文章标题" align="center" prop="topicId">
        <template #default="scope">
          {{ getGeneratedTitleById(scope.row.topicId) }}
        </template>
      </el-table-column>
      <el-table-column label="推送时间" align="center" prop="pushTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.pushTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="推送状态" align="center" prop="pushStatus">
        <template #default="scope">
          <el-tag :type="scope.row.pushStatus == 1 ? 'success' : 'danger'">
            {{ scope.row.pushStatus == 1 ? '成功' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">详情</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pushRecord:pushRecord:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加AI生成文章详情框 -->
    <el-dialog :title="'AI生成文章详情'" v-model="detailOpen" width="700px" append-to-body>
      <div class="article-detail" v-if="articleDetail.id">
        <div class="article-header">
          <h2 class="article-title">{{ articleDetail.title }}</h2>
        </div>
        <div class="article-summary">
          <h4>摘要</h4>
          <div class="summary-content">{{ articleDetail.summary }}</div>
        </div>
        <div class="article-content">
          <h4>内容</h4>
          <div class="content-text" v-html="formatContent(articleDetail.content)"></div>
        </div>
      </div>
      <div v-else class="loading-text">加载中...</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PushRecord">
import { listPushRecord, getPushRecord, delPushRecord, addPushRecord, updatePushRecord } from "@/api/pushRecord/pushRecord";
import { listCircle } from "@/api/circle/circle";
import { listDigest, getDigest } from "@/api/digest/digest";

const { proxy } = getCurrentInstance();
const pushRecordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const circleOptions = ref([]); 
const digestOptions = ref([]);

// 添加详情框相关变量
const detailOpen = ref(false);
const articleDetail = ref({
  id: null,
  title: '',
  summary: '',
  content: ''
});

// 推送状态选项
const pushStatusOptions = ref([
  { value: "0", label: "失败" },
  { value: "1", label: "成功" }
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    circleId: null,
    circleName: null, 
    topicId: null,
    generatedTitle: null,
    pushTime: null,
    pushStatus: null,
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询圈子热搜推送记录列表 */
function getList() {
  loading.value = true;
  listPushRecord(queryParams.value).then(response => {
    pushRecordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 获取圈子列表
function getCircleList() {
  listCircle().then(response => {
    if (response.code === 200 && response.rows) {
      circleOptions.value = response.rows.map(item => ({
        id: item.id,
        name: item.circleName || `圈子${item.id}`
      }));
    } else {
      circleOptions.value = [];
      proxy.$modal.msgError("获取圈子列表失败");
    }
  }).catch(() => {
    circleOptions.value = [];
    proxy.$modal.msgError("获取圈子列表失败");
  });
}

// 添加获取圈子名称的方法
function getCircleNameById(id) {
  if (!id) return '';
  const circle = circleOptions.value.find(item => item.id === id);
  return circle ? circle.name : `圈子${id}`;
}

// 获取AI生成文章列表
function getDigestList() {
  listDigest().then(response => {
    if (response.code === 200 && response.rows) {
      digestOptions.value = response.rows.map(item => ({
        id: item.id,
        title: item.generated_title || `AI生成文章${item.id}`
      }));
    } else {
      digestOptions.value = [];
      proxy.$modal.msgError("获取AI生成文章列表失败");
    }
  }).catch(() => {
    digestOptions.value = [];
    proxy.$modal.msgError("获取AI生成文章列表失败");
  });
}

// 添加获取AI生成文章标题的方法
function getGeneratedTitleById(id) {
  if (!id) return '';
  const digest = digestOptions.value.find(item => item.id === id);
  return digest ? digest.title : `AI生成文章${id}`;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    circleId: null,
    topicId: null,
    generatedTextId: null,
    pushTime: null,
    pushStatus: null,
    createdBy: null,
    createdTime: null,
    updatedBy: null,
    updatedTime: null,
    deletedFlag: null
  };
  proxy.resetForm("pushRecordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加圈子热搜推送记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getPushRecord(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改圈子热搜推送记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pushRecordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePushRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPushRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除圈子热搜推送记录编号为"' + _ids + '"的数据项？').then(function() {
    return delPushRecord(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}



/** 导出按钮操作 */
function handleExport() {
  proxy.download('pushRecord/pushRecord/export', {
    ...queryParams.value
  }, `pushRecord_${new Date().getTime()}.xlsx`)
}

// 格式化文章内容，将\n转换为<br>
function formatContent(content) {
  if (!content) return '';
  return content.replace(/\n/g, '<br>');
}

/** 详情按钮操作 */
function handleDetail(row) {
  // 重置详情
  articleDetail.value = {
    id: null,
    title: '',
    summary: '',
    content: ''
  };
  
  // 打开详情框
  detailOpen.value = true;
  
  // 获取AI生成文章详情
  if (row.generatedTextId) {
    getDigest(row.generatedTextId).then(response => {
      if (response.code === 200 && response.data) {
        articleDetail.value = {
          id: response.data.id,
          title: response.data.generatedTitle || '无标题',
          summary: response.data.summaryContent || '无摘要',
          content: response.data.generatedArticle || '无内容'
        };
      } else {
        proxy.$modal.msgError("获取AI生成文章详情失败");
      }
    }).catch(() => {
      proxy.$modal.msgError("获取AI生成文章详情失败");
    });
  } else {
    proxy.$modal.msgError("该记录没有关联AI生成文章");
  }
}

getCircleList();
getDigestList();
getList();
</script>

<style scoped>
.push-status :deep(.el-select) {
  width: 180px; 
}
.generated_title :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 80px;
}

/* 添加文章详情样式 */
.article-detail {
  padding: 10px;
}

.article-header {
  text-align: center;
  margin-bottom: 20px;
}

.article-title {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.article-summary {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.article-summary h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #606266;
}

.summary-content {
  color: #606266;
  line-height: 1.6;
}

.article-content h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #606266;
}

.content-text {
  line-height: 1.8;
  color: #303133;
  text-align: justify;
}

.loading-text {
  text-align: center;
  padding: 30px;
  color: #909399;
  font-size: 16px;
}
</style>